import 'package:flutter/material.dart';
import 'package:pool_english/services/settings_service.dart';

class ExamPage extends StatefulWidget {
  const ExamPage({super.key});

  @override
  State<ExamPage> createState() => _ExamPageState();
}

class _ExamPageState extends State<ExamPage> {
  int _currentIndex = 0;
  final int _totalQuestions = 30;
  final List<String?> _userAnswers = List.filled(30, null);
  final List<Set<String>> _excludedOptions = List.generate(30, (_) => {});
  bool get _isCompleted => !_userAnswers.contains(null);
  
  // 添加模式状态
  int _mode = 0;  // 默认做题模式
  late PageController _pageController;  // 添加 PageController

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: _currentIndex);
    _loadSettings();
  }

  @override
  void dispose() {
    _pageController.dispose();  // 释放控制器
    super.dispose();
  }

  Future<void> _loadSettings() async {
    final mode = await SettingsService.getExamMode();
    if (mounted) {
      setState(() {
        _mode = mode;
        print(mode);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text(
          '小明的考试任务',
          style: TextStyle(fontSize: 16),
        ),
        actions: [
          Center(
            child: Padding(
              padding: const EdgeInsets.only(right: 16),
              child: Text(
                '${_currentIndex + 1}/$_totalQuestions',
                style: const TextStyle(fontSize: 14),
              ),
            ),
          ),
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: PageView.builder(
                controller: _pageController,
                physics: const BouncingScrollPhysics(),  // 启用滑动，并使用弹性效果
                onPageChanged: (index) {
                  setState(() {
                    _currentIndex = index;
                  });
                },
                itemCount: _totalQuestions,
                itemBuilder: (context, index) => SingleChildScrollView(
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 题目
                        Text(
                          '${index + 1}. 小王同学想利用中国知网平台，查询近一个月发表的最新文献信息，她可以利用的数据库是哪个（）？',
                          style: const TextStyle(fontSize: 16),
                        ),
                        const SizedBox(height: 20),
                        // 选项
                        _buildOption('A', '中国学术期刊网络出版总库'),
                        _buildOption('B', '中国优秀硕士学位论文全文数据库'),
                        _buildOption('C', '中国学术期刊(网络版)库'),
                        _buildOption('D', '科技项目成果库(知网版)和精品科普库'),
                        const SizedBox(height: 20),
                        // 只在背题模式下显示解析
                        if (_mode == 1 && _userAnswers[index] != null) ...[
                          const Divider(),
                          const Text(
                            '解析：',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 8),
                          const Text(
                            '选择中国学术期刊网络出版总库，可以清智地查询近1个月的最新文献信息。',
                            style: TextStyle(fontSize: 14),
                          ),
                        ],
                      ],
                    ),
                  ),
                ),
              ),
            ),
            // 底部操作栏
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withAlpha(26),
                    blurRadius: 4,
                    offset: const Offset(0, -2),
                  ),
                ],
              ),
              padding: EdgeInsets.only(
                left: 16,
                right: 16,
                top: 12,
                bottom: MediaQuery.of(context).padding.bottom + 12,
              ),
              child: Row(
                children: [
                  IconButton(
                    onPressed: _showAnswerSheet,
                    icon: const Icon(Icons.assignment_outlined),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: _mode == 0
                        ? ElevatedButton(
                            onPressed: _isCompleted ? () {
                              _showAnswerSheet();
                            } : null,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue,
                              disabledBackgroundColor: Colors.grey,
                              padding: const EdgeInsets.symmetric(vertical: 12),
                            ),
                            child: const Text(
                              '交卷',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                              ),
                            ),
                          )
                        : Row(
                            children: [
                              if (_currentIndex > 0)
                                Expanded(
                                  child: ElevatedButton(
                                    onPressed: _previousQuestion,
                                    child: const Text('上一题'),
                                  ),
                                ),
                              if (_currentIndex > 0) const SizedBox(width: 16),
                              Expanded(
                                child: ElevatedButton(
                                  onPressed: _nextQuestion,
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.blue,
                                    foregroundColor: Colors.white,
                                  ),
                                  child: Text(
                                    _currentIndex < _totalQuestions - 1 ? '下一题' : '完成',
                                  ),
                                ),
                              ),
                            ],
                          ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildOption(String option, String content) {
    final isSelected = _userAnswers[_currentIndex] == option;
    final isExcluded = _excludedOptions[_currentIndex].contains(option);
    final isCorrect = option == 'A'; // 假设正确答案是A
    final showResult = _mode == 1 && isSelected; // 只在背题模式下显示对错

    return GestureDetector(
      onTap: () {
        if (_userAnswers[_currentIndex] != null || isExcluded) return;
        setState(() {
          _userAnswers[_currentIndex] = option;
        });
        
        if (_mode == 0 && _currentIndex < _totalQuestions - 1) {
          Future.delayed(const Duration(milliseconds: 200), () {
            if (mounted) {
              setState(() {
                _currentIndex++;
              });
              _pageController.animateToPage(
                _currentIndex,
                duration: const Duration(milliseconds: 200),
                curve: Curves.easeInOut,
              );
            }
          });
        }
        
        if (_isCompleted) {
          _showAnswerSheet();
        }
      },
      onLongPress: () {
        if (_userAnswers[_currentIndex] != null) return;
        setState(() {
          if (isExcluded) {
            _excludedOptions[_currentIndex].remove(option);
          } else {
            _excludedOptions[_currentIndex].add(option);
          }
        });
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: isExcluded 
              ? Colors.grey.withAlpha(26)
              : showResult
                  ? (isCorrect ? Colors.blue.withAlpha(26) : Colors.red.withAlpha(26))
                  : isSelected  // 选中时显示淡蓝色背景
                      ? Colors.blue.withAlpha(26)
                      : Colors.white,
          border: Border.all(
            color: isExcluded
                ? Colors.grey
                : showResult
                    ? (isCorrect ? Colors.blue : Colors.red)
                    : isSelected  // 选中时显示蓝色边框
                        ? Colors.blue
                        : Colors.grey.withAlpha(77),
          ),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            Text(
              option,
              style: TextStyle(
                fontSize: 16,
                color: isExcluded
                    ? Colors.grey
                    : showResult
                        ? (isCorrect ? Colors.blue : Colors.red)
                        : isSelected  // 选中时显示蓝色文字
                            ? Colors.blue
                            : Colors.black87,
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                content,
                style: TextStyle(
                  fontSize: 14,
                  color: isExcluded ? Colors.grey : null,
                ),
              ),
            ),
            if (showResult)  // 只在背题模式下显示对错图标
              Icon(
                isCorrect ? Icons.check_circle : Icons.cancel,
                color: isCorrect ? Colors.blue : Colors.red,
              ),
          ],
        ),
      ),
    );
  }

  void _showAnswerSheet() {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) => SingleChildScrollView(
        child: AnswerSheet(
          userAnswers: _userAnswers,
          currentIndex: _currentIndex,
          mode: _mode,
          onQuestionSelected: (index) {
            Navigator.pop(context);
            setState(() {
              _currentIndex = index;
            });
          },
        ),
      ),
    );
  }

  void _previousQuestion() {
    if (_currentIndex > 0) {
      setState(() {
        _currentIndex--;
      });
      _pageController.animateToPage(
        _currentIndex,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  void _nextQuestion() {
    if (_currentIndex < _totalQuestions - 1) {
      setState(() {
        _currentIndex++;
      });
      _pageController.animateToPage(
        _currentIndex,
        duration: const Duration(milliseconds: 200),
        curve: Curves.easeInOut,
      );
    }
  }
}

// 答题卡组件
class AnswerSheet extends StatelessWidget {
  final List<String?> userAnswers;
  final int currentIndex;
  final Function(int) onQuestionSelected;
  final int mode;

  const AnswerSheet({
    super.key,
    required this.userAnswers,
    required this.currentIndex,
    required this.onQuestionSelected,
    required this.mode,
  });

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
        padding: const EdgeInsets.all(16),
        constraints: BoxConstraints(
          maxHeight: MediaQuery.of(context).size.height * 0.8,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '答题卡',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(
                  '已答${userAnswers.where((answer) => answer != null).length}/${userAnswers.length}题',
                  style: const TextStyle(
                    fontSize: 14,
                    color: Colors.grey,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Flexible(
              child: GridView.builder(
                shrinkWrap: true,
                physics: const BouncingScrollPhysics(),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 5,
                  mainAxisSpacing: 12,
                  crossAxisSpacing: 12,
                  childAspectRatio: 1,
                ),
                itemCount: userAnswers.length,
                itemBuilder: (context, index) {
                  final isAnswered = userAnswers[index] != null;
                  final isCorrect = userAnswers[index] == 'A';
                  final isCurrent = index == currentIndex;

                  return GestureDetector(
                    onTap: () => onQuestionSelected(index),
                    child: Container(
                      decoration: BoxDecoration(
                        color: isAnswered
                            ? (mode == 1  // 只在背题模式下显示对错颜色
                                ? (isCorrect ? Colors.blue.withAlpha(26) : Colors.red.withAlpha(26))
                                : Colors.blue.withAlpha(26))  // 做题模式统一使用淡蓝色
                            : Colors.grey.withAlpha(26),
                        border: Border.all(
                          color: isCurrent
                              ? Colors.blue
                              : isAnswered
                                  ? (mode == 1  // 只在背题模式下显示对错颜色
                                      ? (isCorrect ? Colors.blue : Colors.red)
                                      : Colors.blue)  // 做题模式统一使用蓝色
                                  : Colors.grey.withAlpha(77),
                          width: isCurrent ? 2 : 1,
                        ),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Center(
                        child: Text(
                          '${index + 1}',
                          style: TextStyle(
                            color: isCurrent
                                ? Colors.blue
                                : isAnswered
                                    ? (mode == 1  // 只在背题模式下显示对错颜色
                                        ? (isCorrect ? Colors.blue : Colors.red)
                                        : Colors.blue)  // 做题模式统一使用蓝色
                                    : Colors.black87,
                            fontWeight: isCurrent ? FontWeight.bold : FontWeight.normal,
                          ),
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
            const SizedBox(height: 20),
            if (mode == 0)
              Padding(
                padding: const EdgeInsets.only(bottom: 20),
                child: SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: !userAnswers.contains(null)
                        ? () {
                            Navigator.pop(context);
                          }
                        : null,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                      padding: const EdgeInsets.symmetric(vertical: 12),
                      disabledBackgroundColor: Colors.grey,
                    ),
                    child: const Text(
                      '交卷',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                      ),
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
} 